//
//  UIView+Category.m
//  AutoMart
//
//  Created by Abner on 2017/7/28.
//  Copyright © 2017年 Abner. All rights reserved.
//

#import "Category.h"
#import <CoreText/CoreText.h>
#import <CommonCrypto/CommonDigest.h>

@implementation UIView (Category)

- (void)setX:(CGFloat)x
{
    CGRect frame = self.frame;
    frame.origin.x = x;
    self.frame = frame;
}

- (void)setY:(CGFloat)y
{
    CGRect frame = self.frame;
    frame.origin.y = y;
    self.frame = frame;
}

- (CGFloat)x
{
    return self.frame.origin.x;
}

- (CGFloat)y
{
    return self.frame.origin.y;
}

- (void)setCenterX:(CGFloat)centerX
{
    CGPoint center = self.center;
    center.x = centerX;
    self.center = center;
}

- (CGFloat)centerX
{
    return self.center.x;
}

- (void)setCenterY:(CGFloat)centerY
{
    CGPoint center = self.center;
    center.y = centerY;
    self.center = center;
}

- (CGFloat)centerY
{
    return self.center.y;
}

- (void)setWidth:(CGFloat)width
{
    CGRect frame = self.frame;
    frame.size.width = width;
    self.frame = frame;
}

- (void)setHeight:(CGFloat)height
{
    CGRect frame = self.frame;
    frame.size.height = height;
    self.frame = frame;
}

- (CGFloat)height
{
    return self.frame.size.height;
}

- (CGFloat)width
{
    return self.frame.size.width;
}

- (CGFloat)right
{
    return self.frame.size.width+self.frame.origin.x;
}

- (void)setRight:(CGFloat)right
{
    CGRect frame = self.frame;
    frame.origin.x = right - frame.size.width;
    self.frame = frame;
}

- (CGFloat)bottom
{
    return self.frame.size.height+self.frame.origin.y;
}

- (void)setBottom:(CGFloat)bottom
{
    CGRect frame = self.frame;
    frame.origin.y = bottom - frame.size.height;
    self.frame = frame;
}

- (void)setSize:(CGSize)size
{
    CGRect frame = self.frame;
    frame.size = size;
    self.frame = frame;
}

- (CGSize)size
{
    return self.frame.size;
}

- (void)setOrigin:(CGPoint)origin
{
    CGRect frame = self.frame;
    frame.origin = origin;
    self.frame = frame;
}

- (CGPoint)origin
{
    return self.frame.origin;
}

@end

@implementation NSObject (Category)

- (BOOL)isValidString
{
    return self != nil && [self isKindOfClass:[NSString class]] && [(NSString *)self length] > 0 && ![self isEqual:@"null"] && ![self isEqual:@"(null)"];
}

- (BOOL)isValidArray
{
    return ![self isKindOfClass:[NSNull class]] &&
    self != nil &&
    [self isKindOfClass:[NSArray class]] &&
    [(NSArray *)self count] > 0;
}

- (BOOL)isValidDict
{
    return ![self isKindOfClass:[NSNull class]] &&
    self != nil &&
    [self isKindOfClass:[NSDictionary class]]
    && [(NSDictionary *)self allKeys].count > 0;
}

@end

@implementation NSString (Category)

- (BOOL)isRightPhoneNum
{
    NSString *newNum = @"^1\\d{10}$";
    NSString *pattern = [NSString stringWithFormat:@"(%@)",newNum];
    NSRegularExpression *regularExpression = [[NSRegularExpression alloc] initWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:nil];
    NSString *mobile = [self stringByReplacingOccurrencesOfString:@" " withString:@""];
    if (mobile.length != 11) {
        return NO;
    }
    
    // 无符号整型数据接收匹配的数据的数目
    NSUInteger numbersOfMatch = [regularExpression numberOfMatchesInString:mobile options:NSMatchingReportProgress range:NSMakeRange(0, mobile.length)];
    if (numbersOfMatch > 0)
    {
        if (!(self.length == 11)) {
            return NO;
        }
        else
        {
            return YES;
        }
    }
    else
    {
        return NO;
    }
}

- (NSString *)safetyPhoneNum
{
    return [self stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
}

- (NSString *)standardPriceFormat
{
    //整数
    NSString* str11;
    //小数点之后的数字
    NSString* str22;
    if ([self containsString:@"."])
    {
        NSArray* array = [self componentsSeparatedByString:@"."];
        str11 = array[0];
        str22 = array[1];
    }
    else
    {
        str11 = self;
    }
    int count = 0;
    long long int a = str11.longLongValue;
    while (a != 0)
    {
        count++;
        a /= 10;
    }
    NSMutableString *string = [NSMutableString stringWithString:str11];
    NSMutableString *newstring = [NSMutableString string];
    while (count > 3) {
        count -= 3;
        NSRange rang = NSMakeRange(string.length - 3, 3);
        NSString *str = [string substringWithRange:rang];
        [newstring insertString:str atIndex:0];
        [newstring insertString:@"," atIndex:0];
        [string deleteCharactersInRange:rang];
    }
    [newstring insertString:string atIndex:0];
    if ([self containsString:@"."])
    {
        //包含小数点
        //返回的数字
        NSString* str33;
        if (str22.length>0) {
            //小数点后面有数字
            str33 = [NSString stringWithFormat:@"%@.%@",newstring,str22];
        } else {
            //没有数字
            str33 = [NSString stringWithFormat:@"%@",newstring];
        }
        return str33;
    }
    else
    {
        //不包含小数点
        return newstring;
    }
}

#pragma mark - 32位 小写
+ (NSString *)MD5ForLower32Bate:(NSString *)str
{
    //要进行UTF8的转码
    const char* input = [str UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(input, (CC_LONG)strlen(input), result);
    
    NSMutableString *digest = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for (NSInteger i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [digest appendFormat:@"%02x", result[i]];
    }
    
    return digest;
}

#pragma mark - 32位 大写
+ (NSString *)MD5ForUpper32Bate:(NSString *)str
{
    //要进行UTF8的转码
    const char* input = [str UTF8String];
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    CC_MD5(input, (CC_LONG)strlen(input), result);
    
    NSMutableString *digest = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    for (NSInteger i = 0; i < CC_MD5_DIGEST_LENGTH; i++) {
        [digest appendFormat:@"%02X", result[i]];
    }
    
    return digest;
}

#pragma mark - 16位 大写
+ (NSString *)MD5ForUpper16Bate:(NSString *)str
{
    NSString *md5Str = [self MD5ForUpper32Bate:str];
    
    NSString  *string;
    for (int i=0; i<24; i++) {
        string=[md5Str substringWithRange:NSMakeRange(8, 16)];
    }
    return string;
}

#pragma mark - 16位 小写
+ (NSString *)MD5ForLower16Bate:(NSString *)str
{
    NSString *md5Str = [self MD5ForLower32Bate:str];
    
    NSString  *string;
    for (int i=0; i<24; i++) {
        string=[md5Str substringWithRange:NSMakeRange(8, 16)];
    }
    return string;
}

+ (NSString *)MD5:(NSString *)str
{
    const char *cStr = [str UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result);
    return [NSString stringWithFormat:
            @"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}

+ (NSInteger)compareDateWithNow:(NSString*)aDate
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    formatter.timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];//东八区时间
    NSDate *nowDate = [NSDate date];
    NSString *currentTimeString = [formatter stringFromDate:nowDate];
    
    NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init];
    [dateformatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *dta = [[NSDate alloc] init];
    NSDate *dtb = [[NSDate alloc] init];
    dta = [dateformatter dateFromString:aDate];
    dtb = [dateformatter dateFromString:currentTimeString];
    NSComparisonResult result = [dta compare:dtb];
    if (result == NSOrderedAscending)
    {
        //        //bDate比aDate大 现在时间大
        return 1;
    }
    else if (result == NSOrderedDescending)
    {
        //        //bDate比aDate小 现在时间小
        return -1;
    }
    else
    {
        return 0;
    }
}

@end

@implementation UICollectionView (Category)

- (void)setMJHeaderWithTarget:(id)target
         withRefreshingAction:(SEL)refreshingAction
{
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:target refreshingAction:refreshingAction];
    
    // 设置自动切换透明度(在导航栏下面自动隐藏)
    header.automaticallyChangeAlpha = YES;
    
    // 隐藏时间
    header.lastUpdatedTimeLabel.hidden = YES;
    
    // 设置header
    self.mj_header = header;
}


- (void)setMJFooterWithTarget:(id)target
         withRefreshingAction:(SEL)refreshingAction
{
    MJRefreshAutoFooter *footer = [MJRefreshAutoFooter footerWithRefreshingTarget:target refreshingAction:refreshingAction];
    footer.triggerAutomaticallyRefreshPercent = -400;
    
    //    MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:target refreshingAction:refreshingAction];
    //    [footer setTitle:NSLocalizedString(@"Footer.Idle", nil) forState:MJRefreshStateIdle];
    //    [footer setTitle:NSLocalizedString(@"Footer.Refreshing", nil)forState:MJRefreshStateRefreshing];
    //    [footer setTitle:NSLocalizedString(@"Footer.NoMoreData", nil) forState:MJRefreshStateNoMoreData];
    //    footer.stateLabel.font = [UIFont systemFontOfSize:12];
    //    footer.stateLabel.textColor = [UIColor lightGrayColor];
    //    footer.ignoredScrollViewContentInsetBottom = 0.0;
    [footer setHeight:0.5];
    self.mj_footer = footer;
}

@end

@implementation UITableView (Category)

- (void)setMJHeaderWithTarget:(id)target
         withRefreshingAction:(SEL)refreshingAction
{
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:target refreshingAction:refreshingAction];
    // 设置自动切换透明度(在导航栏下面自动隐藏)
    header.automaticallyChangeAlpha = YES;
    // 隐藏时间
    header.lastUpdatedTimeLabel.hidden = YES;
    // 设置header
    self.mj_header = header;
}


- (void)setMJFooterWithTarget:(id)target
         withRefreshingAction:(SEL)refreshingAction
{
    MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:target refreshingAction:refreshingAction];
    [footer setTitle:@"上拉加载更多" forState:MJRefreshStateIdle];
    [footer setTitle:@"正在努力加载..." forState:MJRefreshStateRefreshing];
    [footer setTitle:@"已全部加载完毕" forState:MJRefreshStateNoMoreData];
    footer.stateLabel.font = [UIFont systemFontOfSize:12];
    footer.stateLabel.textColor = [UIColor lightGrayColor];
    footer.ignoredScrollViewContentInsetBottom = 0.0;
    self.mj_footer = footer;
}

@end

@implementation UIImage (Category)

+ (UIImage *)createImageWithColor:(UIColor *)color
{
    CGRect rect = CGRectMake(0.0, 0.0, 1.0, 1.0);
    UIGraphicsBeginImageContext(rect.size);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

- (UIImage *)imageWithColor:(UIColor *)color
{
    UIGraphicsBeginImageContextWithOptions(self.size, NO, self.scale);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(context, 0, self.size.height);
    CGContextScaleCTM(context, 1.0, -1.0);
    CGContextSetBlendMode(context, kCGBlendModeNormal);
    CGRect rect = CGRectMake(0, 0, self.size.width, self.size.height);
    CGContextClipToMask(context, rect, self.CGImage);
    [color setFill];
    CGContextFillRect(context, rect);
    UIImage*newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

@end

@implementation UILabel (Category)

- (void)textAlignmentLeftAndRight
{
    CGSize textSize = [self.text boundingRectWithSize:CGSizeMake(self.width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesFontLeading attributes:@{NSFontAttributeName:self.font} context:nil].size;
    CGFloat margin = (self.width - textSize.width)/(self.text.length - 1);
    NSNumber *number = [NSNumber numberWithFloat:margin];
    NSMutableAttributedString *attrs = [[NSMutableAttributedString alloc] initWithString:self.text];
    [attrs addAttribute:(id)kCTKernAttributeName value:number range:NSMakeRange(0, self.text.length - 1)];
    self.attributedText = attrs;
}

- (void)changeLineSpace:(CGFloat)space
{
    NSString *labelText = self.text;
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:labelText];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:space];
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [labelText length])];
    self.attributedText = attributedString;
    [self sizeToFit];
}

- (void)changeWordSpace:(CGFloat)space
{
    NSString *labelText = self.text;
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:labelText attributes:@{NSKernAttributeName:@(space)}];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [labelText length])];
    self.attributedText = attributedString;
    [self sizeToFit];
}

- (void)changeLineSpace:(CGFloat)lineSpace AndWordSpace:(CGFloat)wordSpace
{
    NSString *labelText = self.text;
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:labelText attributes:@{NSKernAttributeName:@(wordSpace)}];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle setLineSpacing:lineSpace];
    [attributedString addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, [labelText length])];
    self.attributedText = attributedString;
    [self sizeToFit];
}

@end
